using System;
using System.Web;
using System.Web.UI;

namespace ContinualFlame.Locus
{	
	public partial class JoinGame : System.Web.UI.Page
	{
		protected bool validCreds = false;
		
		protected void Page_Load(object sender, EventArgs e)
		{
			string id = Request.Params["id"];
			string key = Request.Params["key"];			
			string dn = Request.Params["dn"];
			
			// sanity check inputs (throws if malformed)
			new Guid(id);
			new Guid(key);
			
			Session s = SessionManager.Instance.GetSessionById(id);
			
			if (s != null && (s.PlayerKey == key || s.GmKey == key))
			{
				validCreds = true;
				
				if (dn != null && IsPostBack)
				{						
					// set up session for user
					ClientInfo ci = new ClientInfo();
					ci.DisplayName = dn;
					ci.IsGm = (key == s.GmKey);
					ci.SessionId = Guid.NewGuid().ToString();
					
					Response.Cookies.Add(new HttpCookie(
						ContinualFlame.Locus.Session.SessionCookieName, 
					    ci.SessionId));
					
					s.AuthorizedClients.Add(ci.SessionId, ci);
					
					string dest = String.Format("GameTable.html?id={0}", id);
					Response.Redirect(dest);
				}
			}
		}
	}
}
